import 'dart:io';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xcite/core/services/open_launcher.dart';

import '../../core/providers/team_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/utils/popup_helper.dart';

class TeamCreationScreen extends ConsumerStatefulWidget {
  const TeamCreationScreen({super.key});

  @override
  ConsumerState<TeamCreationScreen> createState() => _TeamCreationScreenState();
}

class _TeamCreationScreenState extends ConsumerState<TeamCreationScreen> {
  final TextEditingController _teamNameController = TextEditingController();
  final TextEditingController _maxMembersController = TextEditingController();
  final TextEditingController _deadlineController = TextEditingController();

  String? _selectedImagePath;
  bool _isCreating = false;

  @override
  void dispose() {
    _teamNameController.dispose();
    _maxMembersController.dispose();
    _deadlineController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [_buildTopBar(), Expanded(child: _buildMainContent())].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child:
          [
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black,
              ),
              child:
                  Icon(
                    Icons.arrow_back_ios_new,
                  ).iconSize(20.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: () => GoRouter.of(context).pop()),
            Spacer(),
            Text('Team')
                .fontSize(24.sp)
                .fontWeight(FontWeight.bold)
                .textColor(Colors.black)
                .fontFamily('PoetsenOne'),
            Spacer(),
            SizedBox(width: 36.w),
          ].toRow(),
    );
  }

  Widget _buildMainContent() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: [
        SizedBox(height: 40.h),
        _buildInputSection('Team Name', _teamNameController, 'name'),
        SizedBox(height: 24.h),
        _buildInputSection(
          'Limit the number of people',
          _maxMembersController,
          '12',
        ),
        SizedBox(height: 24.h),
        _buildDateInputSection(),
        SizedBox(height: 24.h),
        _buildImageSection(),
        SizedBox(height: 60.h),
        _buildCreateButton(),
        SizedBox(height: 16.h),
        _buildEulaLink(),
        SizedBox(height: 40.h),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildInputSection(
    String label,
    TextEditingController controller,
    String hint,
  ) {
    return [
      Text(label)
          .fontSize(18.sp)
          .fontWeight(FontWeight.bold)
          .textColor(Colors.white)
          .fontFamily('PoetsenOne'),
      SizedBox(height: 12.h),
      Container(
        height: 56.h,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/team_input.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: TextField(
          controller: controller,
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
          decoration: InputDecoration(
            hintText: hint,
            hintStyle: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
              fontFamily: 'PoetsenOne',
            ),
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 20.w,
              vertical: 16.h,
            ),
          ),
          keyboardType:
              label.contains('number')
                  ? TextInputType.number
                  : TextInputType.text,
        ),
      ),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildDateInputSection() {
    return [
      Text('Entry deadline')
          .fontSize(18.sp)
          .fontWeight(FontWeight.bold)
          .textColor(Colors.white)
          .fontFamily('PoetsenOne'),
      SizedBox(height: 12.h),
      Container(
        height: 56.h,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/team_input.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: TextField(
          controller: _deadlineController,
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
          decoration: InputDecoration(
            hintText: '2025-9-10',
            hintStyle: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[600],
              fontFamily: 'PoetsenOne',
            ),
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 20.w,
              vertical: 16.h,
            ),
          ),
          readOnly: true,
          onTap: _selectDate,
        ),
      ),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildImageSection() {
    return [
      Text('Cover')
          .fontSize(18.sp)
          .fontWeight(FontWeight.bold)
          .textColor(Colors.white)
          .fontFamily('PoetsenOne'),
      SizedBox(height: 12.h),
      Container(
        width: 128.w,
        height: 128.w,
        decoration: BoxDecoration(
          image: DecorationImage(
            image:
                _selectedImagePath != null
                    ? FileImage(File(_selectedImagePath!))
                    : AssetImage('assets/resources/team_image_input_bg.png')
                        as ImageProvider,
            fit: BoxFit.cover,
          ),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child:
            _selectedImagePath == null
                ? Container(
                  width: 18.w,
                  height: 24.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/resources/add.png'),
                      fit: BoxFit.contain,
                    ),
                  ),
                ).center()
                : null,
      ).inkWell(onTap: _selectImage),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildCreateButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/resources/team_button.png'),
          fit: BoxFit.fill,
        ),
      ),
      child:
          _isCreating
              ? SizedBox(
                width: 24.w,
                height: 24.w,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ).center()
              : null,
    ).inkWell(onTap: _isCreating ? null : _createTeam);
  }

  Widget _buildEulaLink() {
    return Text(
      'EULA',
      style: TextStyle(
        fontSize: 16.sp,
        color: Colors.white,
        decoration: TextDecoration.underline,
        decorationColor: Colors.white,
      ),
    ).center().inkWell(
      onTap: () {
        Open.openLaunch(
          'https://www.freeprivacypolicy.com/live/2908db45-eaa5-4be2-bf12-428f9bbadb26',
        );
      },
    );
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now().add(Duration(days: 7)),
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(Duration(days: 365)),
    );
    if (picked != null) {
      _deadlineController.text = '${picked.year}-${picked.month}-${picked.day}';
    }
  }

  Future<void> _selectImage() async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          textDelegate: AssetPickerTextDelegate(),
        ),
      );

      if (result != null && result.isNotEmpty) {
        final AssetEntity asset = result.first;
        final File? file = await asset.file;

        if (file != null) {
          final String localPath = await _copyImageToLocal(file);
          if (mounted) {
            setState(() {
              _selectedImagePath = localPath;
            });
          }
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to select image', context: context);
      }
    }
  }

  Future<String> _copyImageToLocal(File sourceFile) async {
    final Directory appDir = await getApplicationDocumentsDirectory();
    final String fileName =
        '${DateTime.now().millisecondsSinceEpoch}${path.extension(sourceFile.path)}';
    final String localPath = path.join(appDir.path, 'team_covers', fileName);

    final Directory targetDir = Directory(path.dirname(localPath));
    if (!await targetDir.exists()) {
      await targetDir.create(recursive: true);
    }

    final File targetFile = await sourceFile.copy(localPath);
    return targetFile.path;
  }

  Future<void> _createTeam() async {
    if (_teamNameController.text.trim().isEmpty) {
      ToastHelper.error('Please enter team name', context: context);
      return;
    }

    if (_maxMembersController.text.trim().isEmpty) {
      ToastHelper.error('Please enter max members', context: context);
      return;
    }

    final int? maxMembers = int.tryParse(_maxMembersController.text.trim());
    if (maxMembers == null || maxMembers <= 0) {
      ToastHelper.error(
        'Please enter valid number of members',
        context: context,
      );
      return;
    }

    if (_deadlineController.text.trim().isEmpty) {
      ToastHelper.error('Please select entry deadline', context: context);
      return;
    }

    if (_selectedImagePath == null) {
      ToastHelper.error('Please select team cover image', context: context);
      return;
    }

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    setState(() {
      _isCreating = true;
    });

    try {
      final dateParts = _deadlineController.text.split('-');
      final deadline = DateTime(
        int.parse(dateParts[0]),
        int.parse(dateParts[1]),
        int.parse(dateParts[2]),
      );

      final teamNotifier = ref.read(teamProvider.notifier);
      final success = await teamNotifier.createTeam(
        teamName: _teamNameController.text.trim(),
        creatorId: currentUser.id,
        maxMembers: maxMembers,
        registrationDeadline: deadline,
        coverImage: _selectedImagePath!,
      );

      if (mounted) {
        if (success) {
          ToastHelper.success('Team created successfully!', context: context);
          GoRouter.of(context).pop();
        } else {
          ToastHelper.error('Failed to create team', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to create team', context: context);
      }
    } finally {
      if (mounted) {
        setState(() {
          _isCreating = false;
        });
      }
    }
  }
}
